<template>
  <view class="user-list">

    <view v-for="user in $store.state.chat.onlineUser" :key="user.name" class="user-item">

      <image :src="user.avatar" class="avatar"></image>
      <text class="username">{{ user.name.substring(0,6) }}</text>
      <uni-badge class="uni-badge-left-margin" :text="user.messageList.length" absolute="rightTop" size="small">
        <button class="chat-btn" @click="startChat(user.name)" size="mini">开始聊天</button>
      </uni-badge>
    </view>

    <view v-for="user in userList" :key="user.name" class="user-item">
      <image :src="user.avatar" class="avatar"></image>
      <text class="username">{{ user.name.substring(0,6) }}</text>
      <uni-badge class="uni-badge-left-margin" :text="10" absolute="rightTop" size="small">
        <button class="chat-btn-out" @click="startChat(user)" size="mini">聊天记录</button>
      </uni-badge>

    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userList: [{
        id: 1,
        name: '离线用户1',
        avatar: '/static/logo.png'
      }],

    };
  },
  created() {
    let name = this.$store.state.user.nickName
    uni.connectSocket({
      url: 'ws://36.111.170.197:8000/ws/' + name
    });
    uni.onSocketMessage((res) => {
      console.log('收到服务器内容：' + res.data);
      let data = JSON.parse(res.data)
      if (data.type === "JOIN" || data.type === "LEAVE") {
        console.info(data)
        let body = JSON.parse(data.body)
        console.info(body)
        this.$store.state.chat.onlineUser = []
        body.forEach((o, i) => {
          if (o.includes("老师")) {
            return
          }
          let u = {
            id: i,
            name: o,
            avatar: 'http://p2.ssl.qhimg.com/dm/72_72_100/t01153c5aa2c2a26d26.png',
            messageList: []
          }
          this.$store.state.chat.onlineUser.push(u)
        })
      } else {
        this.$store.state.chat.onlineUser.forEach(u => {
          if (data.sender === u.name || data.target === u.name) {
            u.messageList.push(data)
          }
        })
      }
    });
  },
  methods: {
    startChat(name) {
      uni.navigateTo({
        url: '/pages/chatPage?user=' + name
      });
    }
  }
};
</script>

<style>
.user-list {
  padding: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}


.user-item {
border-bottom: 1px solid #999;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-size: 16px;
  flex: 1;
}

.chat-btn {
  background-color: #1aad19;
  color: #ffffff;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
}

.chat-btn-out {
  background-color: #aaaa7f;
  color: #ffffff;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
}
</style>